package com.example.lenovo.tianqi.CityDB.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.example.lenovo.tianqi.MainApplication;
import com.example.lenovo.tianqi.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by lenovo on 2018/1/11.
 */

public class DBManager {
    private static String TAG=DBManager.class.getSimpleName();//获取底层类
    public static final String DB_NAME="china_city.db";
    public static final String PACKAGE_NAME="com.example.lenovo.tianqi";
    public static final String DB_PATH="/data"+ Environment.getDataDirectory().getAbsolutePath()+"/"+PACKAGE_NAME;
    private SQLiteDatabase database;
    private Context conext;
    public DBManager() {

    }
    public static DBManager getInstance(){
        return DBManagerHolder.sInstance;
    }
    private static final class DBManagerHolder{
        public static final DBManager sInstance=new DBManager();
    }
    public SQLiteDatabase getDatabase()
    {
        return database;
    }
    public void openDatabase()
    {
        //PLog.e(TAG, DB_PATH + "/" + DB_NAME);
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }

    private SQLiteDatabase openDatabase(String dbfile) {
        try{
            if(!(new File(dbfile).exists()))
            {
                InputStream is= MainApplication.Instance.getResources().openRawResource(R.raw.china_city); //欲导入的数据库
                FileOutputStream fos=new FileOutputStream(dbfile);
                byte[] buffer=new byte[400000];
                int count;
                while(((count)=is.read(buffer))>0)
                {
                     fos.write(buffer,0,count);
                }
                fos.close();
                is.close();
            }
            return SQLiteDatabase.openOrCreateDatabase(dbfile,null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
